package com.telecom.task;

import com.telecom.mapper.MealMapper;
import com.telecom.mapper.OrderCancelMapper;
import com.telecom.mapper.OrderMapper;
import com.telecom.pojo.entity.Meal;
import com.telecom.pojo.entity.Order;
import com.telecom.pojo.entity.OrderCancel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 订单超时处理定时任务
 */
@Component
@Slf4j
public class OrderTimeoutTask {

    @Resource
    private OrderMapper orderMapper;
    
    @Resource
    private OrderCancelMapper orderCancelMapper;
    
    @Resource
    private MealMapper mealMapper;

    /**
     * 处理支付超时订单
     * 每分钟执行一次，处理15分钟前创建但未支付的订单
     */
    @Scheduled(cron = "0 * * * * ?")
    @Transactional
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", new Date());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        // 查询15分钟前创建但未支付的订单
        List<Order> ordersList = orderMapper.getByPayStatusAndCreateTimeLT(0, time);
        if(ordersList != null && ordersList.size() > 0){
            log.info("发现 {} 个超时订单需要处理", ordersList.size());
            
            ordersList.forEach(order -> {
                try {
                    // 释放套餐库存
                    if (order.getMealId() != null) {
                        Meal meal = mealMapper.selectById(order.getMealId());
                        if (meal != null && meal.getSalesCount() != null && meal.getSalesCount() > 0) {
                            Meal updateMeal = Meal.builder()
                                    .id(order.getMealId())
                                    .salesCount(meal.getSalesCount() - 1)
                                    .updateTime(LocalDateTime.now())
                                    .build();

                            int result = mealMapper.updateById(updateMeal);
                            if (result > 0) {
                                log.info("订单超时取消，套餐 {} 销量减少 1，当前销量：{}", order.getMealId(), meal.getSalesCount() - 1);
                            } else {
                                log.warn("订单超时取消，但套餐 {} 销量减少失败", order.getMealId());
                            }
                        }
                    }

                    // 更新订单状态为已取消
                    orderMapper.updateOrderStatus(order.getId(), 2, 2);
                    
                    // 创建取消记录
                    OrderCancel orderCancel = OrderCancel.builder()
                            .orderId(order.getId())
                            .cancelReason("支付超时，自动取消")
                            .refundAmount(BigDecimal.ZERO)  // 未支付订单，无需退款
                            .refundStatus(1)  // 标记为退款成功（实际无退款）
                            .operatorId(null)  // 系统自动取消
                            .cancelTime(LocalDateTime.now())
                            .refundTime(LocalDateTime.now())
                            .createTime(LocalDateTime.now())
                            .updateTime(LocalDateTime.now())
                            .build();
                    
                    orderCancelMapper.insert(orderCancel);
                    log.info("订单 {} 因支付超时自动取消，已创建取消记录", order.getOrderNumber());
                } catch (Exception e) {
                    log.error("处理超时订单失败，订单ID：{}，错误：{}", order.getId(), e.getMessage());
                }
            });
        } else {
            log.debug("当前没有需要处理的超时订单");
        }
    }
}